package com.tengju.support.domain.model.rule;

import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Rule {

    RuleId ruleId;

    String description;

    List<RuleNode> ruleNodes;

    BizType bizType;

    String createBy;

    String updateBy;


    public boolean evaluate(MetaInfo metaInfo) {
        for (RuleNode ruleNode : ruleNodes) {
            if (ruleNode.getCondition() == null) {
                continue;
            }
            //其中一个condition为true 则返回true
            if (ruleNode.getCondition().evaluate(metaInfo)) {
                return true;
            }
        }
        return false;
    }


    public List<Object> execute(MetaInfo metaInfo) {
        if (CollectionUtils.isEmpty(ruleNodes)) {
            return null;
        }

        for (RuleNode ruleNode : ruleNodes) {
            if (ruleNode.getCondition() == null) {
                continue;
            }

            if (ruleNode.getCondition().evaluate(metaInfo)) {
                if (CollectionUtils.isEmpty(ruleNode.getActions())) {
                    return null;
                }

                List<Object> results = Lists.newArrayList();
                for (Action action : ruleNode.getActions()) {
                    Object result = action.execute(metaInfo);
                    results.add(result);
                }

                return results;
            }

        }
        return Lists.newArrayList();
    }

    public void editRule(Rule newRule) {
        this.description = newRule.getDescription();
        this.ruleNodes = newRule.getRuleNodes();
        this.bizType = getBizType();
        this.updateBy = getUpdateBy();
    }

}
